package com.example.administrator.shihuo.utils;

import android.os.Handler;

import com.example.administrator.shihuo.callback.OkHttpDataListener;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by Administrator on 2016/5/11.
 */
public class OkHttpUtils {


    /**
     * OkHttp普通get请求
     * @param url 网络请求连接
     * @param listener OkHttpDataListener 在实现的方法里面接收数据(在子线程)
     *                 取消请求OkHttpUtils.getInstance().cancelTag("get");
     */
    public static void getStringAsync(final String url, final OkHttpDataListener listener){

        new Thread(new Runnable() {
            @Override
            public void run() {
                //创建一个okhttpClient对象
                OkHttpClient client=new OkHttpClient();
                //创建一个请求对象
                Request request=new Request.Builder()
                        .url(url)
                        .tag("get")
                        .build();
                try {
                    //开始访问网络,拿到响应对象
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        String string = response.body().string();//拿到返回的String
                        listener.okHttpSuccess(string);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
